package com.wms.controller;

import com.wms.config.Result;
import com.wms.util.SysConfig;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.UUID;

@RestController
@RequestMapping("file")
@CrossOrigin
public class FileUploadController {
    @RequestMapping("upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        // File upload logic remains the same
        String oldName = file.getOriginalFilename();
        String lastName = oldName.substring(oldName.lastIndexOf("."));
        String newname = UUID.randomUUID().toString() + lastName;
        File target = new File(SysConfig.UPLOAD_DIR + "/" + newname);
        file.transferTo(target);

        // Return the file access path
        String path = SysConfig.UPLOAD_PATH + "/" + newname;
        return Result.success("上传成功", path);
    }
    // 新增头像上传接口
    @RequestMapping("avatar")
    public Result avatarUpload(@RequestParam("avatar") MultipartFile file) throws IOException {
        String oldName = file.getOriginalFilename();
        String extension = oldName.substring(oldName.lastIndexOf("."));
        String newName = "avatar_" + UUID.randomUUID() + extension;

        // 创建头像存储目录
        File avatarDir = new File(SysConfig.UPLOAD_DIR + "/avatars/");
        if (!avatarDir.exists()) avatarDir.mkdirs();

        File target = new File(avatarDir, newName);
        file.transferTo(target);

        // 返回相对路径
        String path = "/upload/avatars/" + newName; // 直接返回基础路径
        return Result.success("头像上传成功", path);
    }
    // 新增获取默认头像接口
    @GetMapping("avatar/default")
    public Result getDefaultAvatar() {
        File avatarDir = new File(SysConfig.UPLOAD_DIR + "/avatars/");

        if (!avatarDir.exists()) {
            // 返回固定默认头像路径
            return Result.success("/static/default-avatar.png");
        }

        // 直接返回第一个头像文件
        File[] files = avatarDir.listFiles();
        if (files != null && files.length > 0) {
            String firstName = files[0].getName();
            return Result.success("/upload/avatars/" + firstName);
        }

        return Result.fail(500,"未找到默认头像");
    }
}
